<script setup lang="ts">
  import {
    request
  } from '@/api';
  import b64toBlob from 'b64-to-blob';
  import {
    closeToast,
    showLoadingToast,
    showToast,
    type ActionSheetAction
  } from 'vant';
  import {
    onMounted,
    ref
  } from 'vue';
  // 获取用户头像数据

  //   头像的上传
  const showAvatarSheet = ref(false);
  const actions = [{
      name: '相冊'
    },
    {
      name: '拍照'
    },
  ];
  // 选择职业
  const columns = [{
      text: '软件工程师',
      value: '软件工程师'
    },
    {
      text: '医生',
      value: '医生'
    },
    {
      text: '教师',
      value: '教师'
    },
    {
      text: '律师',
      value: '律师'
    },
    {
      text: '会计师',
      value: '会计师'
    },
    {
      text: '销售经理',
      value: '销售经理'
    },
    {
      text: '市场营销专员',
      value: '市场营销专员'
    },
    {
      text: '建筑师',
      value: '建筑师'
    },
    {
      text: '护士',
      value: '护士'
    },
    {
      text: '机械工程师',
      value: '机械工程师'
    }
  ]
  // 打开相机或相册
  const onSelectAvatar = async (item: ActionSheetAction, index: number) => {
    if (index == 0) {
      // 相册上传
      const data = await mk.pickerPhoto()
      console.log(data, '相册上传');
      onUpdateAvatar(data)
    } else if (index == 1) {
      // 拍照上传
      const data = await mk.pickerCamera()
      onUpdateAvatar(data)
      console.log(data, '拍照上传');
    }
  }
  // 封装头像上传的函数
  const onUpdateAvatar = async (data: string) => {
    try {
      // 添加加载效果
      showLoadingToast({
        message: '主上正在加载....',
        forbidClick: true,
        duration: 0
      })
      const image = b64toBlob(data, 'image/jpeg')
      const fd = new FormData()
      fd.append('file', image, Date.now() + '.jpeg')
      const res = await request.post < MkResponse < {
        avatar: string
      } >> ('member/profile/avatar', fd)
      // 加载完成关闭效果
      closeToast()
      // 更新头像 
      profile.value.avatar = res.data.result.avatar 
      // 返回更新时头像同步更新
      const user = mk.queryUser()
      user.avatar = res.data.result.avatar
      mk.updateUser(user)
    } catch (err) {
      console.log(err);
    }
  }

  // 选择日期
  const showBottom = ref(false)
  const now = new Date()
  const birthday = ref([
    now.getFullYear().toString(),
    String(now.getMonth() + 1),
    now.getDate().toString()
    // '2012','01','01'
  ])
  const profile = ref < ProfileInfo > ({}as ProfileInfo)
  onMounted(async () => {
    // 开启加载提示
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });
    const res = await request.get < MkResponse < ProfileInfo >> ('member/profile')
    // 关闭加载提示
    closeToast()
    profile.value = res.data.result
    // 将数组转化为字符串
    birthday.value = profile.value.birthday.split('-')
    console.log(birthday.value, '获取选中的时间');

  })
  const onConfirmBirthDay = () => {
    // 将数组转换为字符串
    profile.value.birthday = birthday.value.join('-')
    console.log('33333', profile.value.birthday);
    showBottom.value = false
  }
  // 所在地区
  const areaColumns = ref < AreaColumns > ()
  const showLocationPopup = ref(false)
  onMounted(async () => {
    const data = await mk.getAreaColumns()
    areaColumns.value = data
  })
  // 选择职业人员
  const onSelectedLocation = (data: {selectedValues: number[]}) => {
    // 处理数据
    // // 省
    // profile.value.provinceCode = data.selectedValues[0]
    // // 市
    // profile.value.cityCode = data.selectedValues[1]
    // // 区
    // profile.value.countyCode = data.selectedValues[2]
    const primary = areaColumns.value?.province_list[data.selectedValues[0]]
    const city = areaColumns.value?.city_list[data.selectedValues[1]]
    const county = areaColumns.value?.county_list[data.selectedValues[2]]
    console.log(primary,city,county,'获取到的省市区');
    // 把上面获取到的省市区赋值给profile 
    profile.value.fullLocation = `${primary} ${city} ${county}`
     // 关闭弹层
    showLocationPopup.value = false
  }
  // 选择职业
  const showPicker = ref(false)
  const onChangeProfession = (data: {selectedValues: string[]}) => {
    console.log(data);
    profile.value.profession = data.selectedValues[0]
    showPicker.value = false
  }
// 点击保存更新信息
const loading = ref(false)
const onsubmit= async ()=>{
  // 加载效果
  // const loading = ref()
 loading.value = true
  await request.put('/member/profile',profile.value)
  loading.value = false
  const user = mk.queryUser()
  user.nickname = profile.value.nickname
  mk.updateUser(user)
  showToast({message:'保存成功'})
}
</script>
<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>

      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
      <van-action-sheet @select="onSelectAvatar" style="padding-bottom: 20px;" v-model:show="showAvatarSheet"
        :actions="actions" cancel-text="取消" close-on-click-action />
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" v-model="profile.birthday" @click="showBottom=true">
      </van-field>
      <van-popup v-model:show="showBottom" position="bottom">
        <!-- 日期-->
        <van-date-picker v-model="birthday" @cancel="showBottom = false" title="选择日期" :min-date="new Date(1975,1,1)"
          @confirm="onConfirmBirthDay" />
      </van-popup>


      <van-field label="所在地" v-model="profile.fullLocation" readonly placeholder="请选择所在地"
        @click="showLocationPopup = true"></van-field>
      <!-- 选择所在地弹层 -->
      <van-popup v-model:show="showLocationPopup" round position="bottom">
        <van-area :area-list="areaColumns" @confirm="onSelectedLocation"></van-area>
      </van-popup>
      <!-- 职业选择弹窗 -->
      <van-field v-model="profile.profession" is-link readonly label="职业" placeholder="选择职业"
        @click="showPicker = true" />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onChangeProfession" />
      </van-popup>
    </van-cell-group>

    <div class="submit" >
      <van-button round block type="primary" @click="onsubmit">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
  .avatar {
    padding: 30px;
    text-align: center;
    background-color: var(--mk-white);
  }

  .avatar-img {
    box-shadow: 0 0 5px var(--mk-gray);
  }

  .avatar-btn {
    color: var(--mk-linear_end);
    margin-top: 10px;
  }

  .gender ::v-deep(.van-cell__title) {
    width: 100px;
    flex: none;
  }

  .van-radio-group {
    display: flex;
    justify-content: space-between;
    height: 36px;
    width: 180px;
  }

  .submit {
    padding: 16px;
  }

</style>
